#!/bin/sh
# Download and build latest version of U-Boot

DEFCONFIG="${1}" # For example "rpi_3_defconfig"
TUPLE="${2}" # For example "aarch64-linux-gnu"

set -ex

U_BOOT_GIT_URL_DEFAULT="https://source.denx.de/u-boot/u-boot.git/"

if [ ! -z "${U_BOOT_GIT_REV}" ]
then
	git clone --depth 1 \
	          --reference-if-able "${WORKDIR}/u-boot" \
	          --branch "${U_BOOT_GIT_REV}" \
	          "${U_BOOT_GIT_URL:-${U_BOOT_GIT_URL_DEFAULT}}" u-boot
else
	git clone --depth 1 \
	          --reference-if-able "${WORKDIR}/u-boot" \
	          "${U_BOOT_GIT_URL:-${U_BOOT_GIT_URL_DEFAULT}}" u-boot
fi

# Collect version of U-Boot
(echo -n u-boot,; git -C u-boot describe --tags --always --abbrev=10) >> versions.csv

# Step into U-Boot directory
cd u-boot

# Apply patches
if [ -d "${U_BOOT_PATCHES_DIR}" ]; then
	git apply "${U_BOOT_PATCHES_DIR}"/*.patch || :
fi

# Set localversion
export LOCALVERSION="johang"

# CROSS_COMPILE must point to a valid compiler path prefix
export CROSS_COMPILE=$(dirname $(which "${TUPLE}-gcc"))/"${TUPLE}-"

# Build U-Boot
make ${MAKEFLAGS} "${DEFCONFIG}" && make ${MAKEFLAGS:--j$(nproc)}
